package com.gewu.pm.ui.fragment;

import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gewu.pm.R;
import com.gewu.pm.aop.SingleClick;
import com.gewu.pm.app.TitleBarFragment;
import com.gewu.pm.bean.FunctionItemBean;
import com.gewu.pm.bean.ReportItemBean;
import com.gewu.pm.ui.MainActivity;
import com.gewu.pm.ui.activity.CommonFunctionSettingActivity;
import com.gewu.pm.ui.activity.MoreReportActivity;
import com.gewu.pm.ui.activity.clockin.ClockInManageActivity;
import com.gewu.pm.ui.activity.customer.DeliveryProviderActivity;
import com.gewu.pm.ui.activity.customer.SalesPersonActivity;
import com.gewu.pm.ui.activity.delivery.DeliveryManagementOrderActivity;
import com.gewu.pm.ui.activity.delivery.DeliveryManagementTerminalActivity;
import com.gewu.pm.ui.activity.delivery.DeliveryProviderReconciliationActivity;
import com.gewu.pm.ui.activity.funds.FreezerManagementActivity;
import com.gewu.pm.ui.activity.funds.GoldBeanManagementActivity;
import com.gewu.pm.ui.activity.home.ReportGoodsSalesActivity;
import com.gewu.pm.ui.activity.home.ReportNoOrderCustomerActivity;
import com.gewu.pm.ui.activity.home.ReportOrderSummaryActivity;
import com.gewu.pm.ui.activity.home.ReportReducedOrderActivity;
import com.gewu.pm.ui.activity.home.ReportTerminalReceivableActivity;
import com.gewu.pm.ui.activity.home.ReportTerminalSalesActivity;
import com.gewu.pm.ui.activity.order.PaymentReceiptActivity;
import com.gewu.pm.ui.activity.order.PendingPaymentActivity;
import com.gewu.pm.ui.activity.order.SalesOrderActivity;
import com.gewu.pm.ui.activity.order.TelegraphicTransferActivity;
import com.gewu.pm.ui.activity.payment.PaymentTermActivity;
import com.gewu.pm.ui.activity.promotion.PromotionManagementActivity;
import com.gewu.pm.ui.activity.report.DailyReportActivity;
import com.gewu.pm.ui.activity.sales.SalesLeadsActivity;
import com.gewu.pm.ui.activity.terminal.TerminalManagementActivity;
import com.gewu.pm.ui.activity.work.PromotionVisitActivity;
import com.gewu.pm.ui.activity.work.VisitManagementActivity;
import com.gewu.pm.ui.adapter.HomeFunctionAdapter;
import com.gewu.pm.ui.adapter.ReportItemAdapter;
import com.gewu.pm.utils.eventbus.EventBean;
import com.gewu.pm.utils.eventbus.EventCode;
import com.hjq.base.BaseAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * 首页 Fragment
 */
public final class HomeFragment extends TitleBarFragment<MainActivity> implements BaseAdapter.OnItemClickListener {

    private RecyclerView rvCommonFunctions;
    private LinearLayout llSettings;
    private RecyclerView rvReports;
    private LinearLayout layoutHomeMore;
    private TextView tvSwitch;
    private TextView tvUserName;
    private ImageView ivUserAvatar;

    private HomeFunctionAdapter functionAdapter;//常用功能
    private ReportItemAdapter reportAdapter;

    /**
     * 常用功能列表
     */
    private List<FunctionItemBean> commonFunctionList;
    /**
     * 所有功能列表
     */
    private List<FunctionItemBean> allFunctionList;
    /**
     * 报表列表
     */
    private List<ReportItemBean> reportList;

    public static HomeFragment newInstance() {
        return new HomeFragment();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.home_fragment;
    }

    @Override
    protected void initView() {
        tvSwitch = findViewById(R.id.tv_switch);
        tvUserName = findViewById(R.id.tv_user_name);
        ivUserAvatar = findViewById(R.id.iv_user_avatar);
        rvCommonFunctions = findViewById(R.id.rv_common_functions);
        llSettings = findViewById(R.id.ll_settings);
        rvReports = findViewById(R.id.rv_reports);
        layoutHomeMore = findViewById(R.id.layout_home_more);
        setOnClickListener(tvSwitch, layoutHomeMore, llSettings);

        // 设置常用功能RecyclerView（4列网格布局）
        GridLayoutManager functionLayoutManager = new GridLayoutManager(getContext(), 4);
        rvCommonFunctions.setLayoutManager(functionLayoutManager);
        functionAdapter = new HomeFunctionAdapter(getContext());
        // 必须在setAdapter之前设置监听器
        functionAdapter.setOnItemClickListener(this);
        rvCommonFunctions.setAdapter(functionAdapter);

        // 设置报表列表（使用2列网格布局）
        GridLayoutManager reportLayoutManager = new GridLayoutManager(getContext(), 2);
        rvReports.setLayoutManager(reportLayoutManager);
        reportAdapter = new ReportItemAdapter(getContext());
        // 必须在setAdapter之前设置监听器
        reportAdapter.setOnItemClickListener(this);
        rvReports.setAdapter(reportAdapter);
    }

    @Override
    protected void initData() {
        commonFunctionList = new ArrayList<>();
        allFunctionList = new ArrayList<>();
        reportList = new ArrayList<>();
        // 初始化所有功能数据
        initAllFunctions();

        // 初始化默认常用功能
        initDefaultCommonFunctions();

        // 初始化报表数据
        initReportData();

        // 刷新界面
        refreshCommonFunctions();
        reportAdapter.setData(reportList);
    }

    @SingleClick
    @Override
    public void onClick(View view) {
        super.onClick(view);
        if (view == llSettings) {//设置
            // 跳转到常用功能设置页面，并传递当前已选择的功能列表（使用EventBus方式）
            CommonFunctionSettingActivity.start(getContext(), commonFunctionList);
        } else if (view == layoutHomeMore) {//查看更多数据报表
            startActivity(MoreReportActivity.class);
        } else if (view == tvSwitch) {//切换
            toast("切换");
        }

    }

    /**
     * 列表点击事件
     */
    @Override
    public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
        if (recyclerView == rvCommonFunctions) {//全部功能
            FunctionItemBean item = functionAdapter.getItem(position);
            // 最后一个是"全部功能"
            if (item.getId().equals("-1")) {
                // 点击"全部功能"，跳转到查看全部功能页面
                CommonFunctionSettingActivity.start(getContext());
            } else {
                // 点击其他功能
                String id = item.getId();
                switch (id) {
                    case "1": //收款单
                        startActivity(PaymentReceiptActivity.class);
                        break;
                    case "2": //电汇收款
                        startActivity(TelegraphicTransferActivity.class);
                        break;
                    case "3": //销售订单
                        startActivity(SalesOrderActivity.class);
                        break;
                    case "4": //代支付
                        startActivity(PendingPaymentActivity.class);
                        break;
                    case "5": //促销管理
                        startActivity(PromotionManagementActivity.class);
                        break;
                    case "6": //终端管理
                        startActivity(TerminalManagementActivity.class);
                        break;
                    case "7": //配送商管理
                        startActivity(DeliveryProviderActivity.class);
                        break;
                    case "8": //业务员管理
                        startActivity(SalesPersonActivity.class);
                        break;
                    case "9": //销售线索
                        startActivity(SalesLeadsActivity.class);
                        break;
                    case "10": //打卡管理
                        startActivity(ClockInManageActivity.class);
                        break;
                    case "11": //冰柜管理
                        startActivity(FreezerManagementActivity.class);
                        break;
                    case "12": //账期单
                        startActivity(PaymentTermActivity.class);
                        break;
                    case "13": //金豆管理
                        startActivity(GoldBeanManagementActivity.class);
                        break;
                    case "14": //拜访管理
                        startActivity(VisitManagementActivity.class);
                        break;
                    case "15": //促销拜访
                        startActivity(PromotionVisitActivity.class);
                        break;
                    case "16": //日报管理
                        startActivity(DailyReportActivity.class);
                        break;
                    case "17": //配送管理-经销
                        startActivity(DeliveryManagementTerminalActivity.class);
                        break;
                    case "18": //配送管理-订单
                        startActivity(DeliveryManagementOrderActivity.class);
                        break;
                    case "19": //配送商对账
                        startActivity(DeliveryProviderReconciliationActivity.class);
                        break;
                }
            }
        } else if (recyclerView == rvReports) {//数据列表
            ReportItemBean item = reportAdapter.getItem(position);
            String id = item.getId();
            // TODO: 跳转到具体的报表页面
            switch (id) {
                case "1": //末下单客户报表
                    startActivity(ReportNoOrderCustomerActivity.class);

                    break;
                case "2": //终端应收报表
                    startActivity(ReportTerminalReceivableActivity.class);

                    break;
                case "3": //订单汇总报表
                    startActivity(ReportOrderSummaryActivity.class);

                    break;
                case "5": //终端销售报表
                    startActivity(ReportTerminalSalesActivity.class);

                    break;
                case "6": //商品销售报表
                    startActivity(ReportGoodsSalesActivity.class);

                    break;
                case "7": //减货订单报表
                    startActivity(ReportReducedOrderActivity.class);

                    break;
            }
        }
    }

    /**
     * 初始化所有功能
     */
    private void initAllFunctions() {
        // 主体功能
        allFunctionList.add(new FunctionItemBean("1", "收款单", R.mipmap.label_receipt_ic));
        allFunctionList.add(new FunctionItemBean("2", "电汇收款", R.mipmap.label_remittance_ic));
        allFunctionList.add(new FunctionItemBean("3", "销售订单", R.mipmap.label_sales_order_ic));
        allFunctionList.add(new FunctionItemBean("4", "代支付", R.mipmap.label_payment_behalf_ic));
        allFunctionList.add(new FunctionItemBean("5", "促销管理", R.mipmap.label_promotion_ic));

        // 客户管理
        allFunctionList.add(new FunctionItemBean("6", "终端管理", R.mipmap.label_terminal_ic));
        allFunctionList.add(new FunctionItemBean("7", "配送商管理", R.mipmap.label_distributor_ic));
        allFunctionList.add(new FunctionItemBean("8", "业务员管理", R.mipmap.label_salesperson_ic));
        allFunctionList.add(new FunctionItemBean("9", "销售线索", R.mipmap.label_sales_leads_ic));
        allFunctionList.add(new FunctionItemBean("10", "打卡管理", R.mipmap.label_attendance_ic));

        // 资金管理
        allFunctionList.add(new FunctionItemBean("19", "配送商对账", R.mipmap.label_delivery_provider_reconciliation_ic));
        allFunctionList.add(new FunctionItemBean("11", "冰柜管理", R.mipmap.label_freezer_ic));
        allFunctionList.add(new FunctionItemBean("12", "账期单", R.mipmap.label_account_period_ic));
        allFunctionList.add(new FunctionItemBean("13", "金豆管理", R.mipmap.label_golden_ic));

        // 外勤管理
        allFunctionList.add(new FunctionItemBean("14", "拜访管理", R.mipmap.label_visit_ic));
        allFunctionList.add(new FunctionItemBean("15", "促销拜访", R.mipmap.label_promotion_visit_ic));
        allFunctionList.add(new FunctionItemBean("16", "日报管理", R.mipmap.label_daily_report_ic));

        // 配送管理
        allFunctionList.add(new FunctionItemBean("17", "配送管理(终端)", R.mipmap.label_courier_management_terminal_ic));
        allFunctionList.add(new FunctionItemBean("18", "配送管理(订单)", R.mipmap.label_courier_management_order_ic));
    }

    /**
     * 初始化默认常用功能
     */
    private void initDefaultCommonFunctions() {
        // 默认添加几个常用功能
        if (allFunctionList.size() > 0) {
            commonFunctionList.add(allFunctionList.get(0)); // 收款单
            commonFunctionList.add(allFunctionList.get(2)); // 销售订单
            commonFunctionList.add(allFunctionList.get(5)); // 终端管理
            commonFunctionList.add(allFunctionList.get(3)); // 代支付
            commonFunctionList.add(allFunctionList.get(16)); // 配送管理(终端)
            commonFunctionList.add(allFunctionList.get(10)); // 配送商对账
        }
    }

    /**
     * 刷新常用功能显示
     */
    private void refreshCommonFunctions() {
        if (functionAdapter == null) {
            return;
        }

        // 创建功能列表（包含实际功能+全部功能按钮）
        List<FunctionItemBean> displayList = new ArrayList<>(commonFunctionList);
        // 添加"全部功能"项
        displayList.add(new FunctionItemBean("-1", getString(R.string.all_functions), R.mipmap.label_all_ic));

        // 设置数据到适配器（setData内部已经调用了notifyDataSetChanged）
        functionAdapter.setData(displayList);
    }

    /**
     * 初始化报表数据（根据首页UI设计）
     */
    private void initReportData() {
        // 直接创建报表列表，不需要分类
        reportList.add(new ReportItemBean("1", "末下单客户报表", "掌控团队整体进度", R.mipmap.report_unordered_customer_ic));
        reportList.add(new ReportItemBean("2", "终端应收报表", "终端报表记录", R.mipmap.report_terminal_receivable_ic));
        reportList.add(new ReportItemBean("3", "订单汇总报表", "查看团队全部订单", R.mipmap.report_order_summary_ic));
        reportList.add(new ReportItemBean("7", "减货订单报表", "减货分析报告", R.mipmap.report_reduce_order_ic));
        reportList.add(new ReportItemBean("5", "终端销售报表", "终端销售分析报告", R.mipmap.report_terminal_sales_ic));
        reportList.add(new ReportItemBean("6", "商品销售报表", "解析商品趋势", R.mipmap.report_product_sales_ic));
        //reportList.add(new ReportItemBean("4", "配送商销售报表", "分析最新销售情况", R.mipmap.report_distributor_sales_ic));
    }

    @Override
    public boolean isStatusBarEnabled() {
        // 使用沉浸式状态栏
        return !super.isStatusBarEnabled();
    }

    @Override
    protected boolean isRegisteredEventBus() {
        return true;
    }

    @Override
    public void onEventBusCome(EventBean event) {
        super.onEventBusCome(event);
        if (event.getCode() == EventCode.COMMON_FUNCTION_UPDATE) {
            // 接收常用功能更新事件
            @SuppressWarnings("unchecked")
            List<FunctionItemBean> updatedFunctions = (List<FunctionItemBean>) event.getData();
            if (updatedFunctions != null) {
                // 更新常用功能列表
                commonFunctionList.clear();
                commonFunctionList.addAll(updatedFunctions);

                // 刷新界面
                refreshCommonFunctions();

                toast("常用功能已更新");
            }
        }
    }
}